package com.mk.cloud.common.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.osgl.util.S;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 模拟http请求<br>
 * 〈功能详细描述〉
 *
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class HttpUtils {
    private static final int SUCCESS = 200;
    private static final int HTTP_TIMEOUT = 60000;
    private static final String DEFAULT_CHART_SET = "UTF-8";
    private static final String JSON_TYPE = "application/json";
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;

    static {
        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();
        // 设置连接池大小
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(HTTP_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(HTTP_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(HTTP_TIMEOUT);
        requestConfig = configBuilder.build();
    }

    /**
     * 执行一个HTTP get请求
     * 编码：utf8
     *
     * @param url 请求的URL地址
     * @return 请求相应的字符串
     */
    public static String doGet(String url) {
        return doGet(url, new String());
    }

    /**
     * 执行一个HTTP get请求
     * 编码：utf8
     *
     * @param url         请求的URL地址
     * @param queryString 请求的参数,格式：name=1&age=2
     * @return 请求相应的字符串
     */
    public static String doGet(String url, String queryString) {
        return doGet(url, queryString, DEFAULT_CHART_SET);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url         请求的URL地址
     * @param queryString 请求的参数,格式：name=1&age=2
     * @param charset     编码
     * @return 请求相应的字符串
     */
    public static String doGet(String url, String queryString, String charset) {
        return doGet(url, queryString, charset, null);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url    请求的URL地址
     * @param params 请求的参数
     * @return 请求相应的字符串
     */
    public static String doGet(String url, Map<String, Object> params) {
        return doGet(url, params, "UTF-8");
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url     请求的URL地址
     * @param params  请求的参数
     * @param charset 编码
     * @return 请求相应的字符串
     */
    public static String doGet(String url, Map<String, Object> params, String charset) {
        return doGet(url, params, charset, null);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url     请求的URL地址
     * @param params  请求的参数
     * @param charset 编码
     * @param headers 要传递的头信息
     * @return
     */
    public static String doGet(String url, Map<String, Object> params, String charset, Map<String, String> headers) {
        StringBuffer str = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null) {
                    str.append(entry.getKey());
                    str.append("=");
                    str.append(entry.getValue());
                    str.append("&");
                }
            }
        }
        return doGet(url, str.toString(), charset, headers);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url         请求的URL地址
     * @param queryString 请求的参数,格式：name=1&age=2
     * @param charset     编码
     * @param headers     要传递的头信息
     * @return 请求相应的字符串
     */
    public static String doGet(String url, String queryString, String charset, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
        HttpGet httpGet = new HttpGet(S.isNotBlank(queryString) ? url + "?" + queryString : url);
        httpGet.setConfig(requestConfig);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        } else {
            httpGet.reset();
        }
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == SUCCESS) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    result = IOUtils.toString(instream, charset);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * 执行一个HTTP get请求
     * 编码：utf8
     *
     * @param url 请求的URL地址
     * @return 请求相应的字符串
     */
    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * 执行一个HTTP get请求
     * 编码：utf8
     *
     * @param url    请求的URL地址
     * @param params 请求的参数
     * @return 请求相应的字符串
     */
    public static String doPost(String url, Map<String, Object> params) {
        return doPost(url, params, DEFAULT_CHART_SET);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url     请求的URL地址
     * @param params  请求的参数
     * @param charset 编码
     * @return 请求相应的字符串
     */
    public static String doPost(String url, Map<String, Object> params, String charset) {
        return doPost(url, params, charset, null);
    }

    /**
     * 执行一个HTTP POST请求
     *
     * @param url     请求的URL地址
     * @param params  请求的参数
     * @param charset 编码
     * @param headers 要传递的cookie
     * @return 请求相应的字符串
     */
    public static String doPost(String url, Map<String, Object> params, String charset, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        } else {
            httpPost.reset();
        }
        List<NameValuePair> pairList = new ArrayList<>(params.size());
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            pairList.add(pair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(charset)));

        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == SUCCESS) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, charset);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 执行一个HTTP get请求
     * 编码：utf8
     *
     * @param url  请求的URL地址
     * @param json 请求的JSON对象
     * @return 请求相应的字符串
     */
    public static String doPost(String url, Object json) {
        return doPost(url, json, DEFAULT_CHART_SET);
    }

    /**
     * 执行一个HTTP post请求 带证书
     * 编码：utf8
     *
     * @param url     请求的URL地址
     * @param json    请求的JSON对象
     * @param sslpath 请求证书地址
     * @param sslpass 证书密码
     * @return 请求相应的字符串
     */
    public static String doPostSSL(String url, Object json, String sslpath, String sslpass) throws Exception {
        return doPostSSL(url, json, DEFAULT_CHART_SET, sslpath, sslpass);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url     请求的URL地址
     * @param json    请求的JSON对象
     * @param charset 编码
     * @return 请求相应的字符串
     */
    public static String doPost(String url, Object json, String charset) {
        return doPost(url, json, charset, null);
    }

    /**
     * 执行一个HTTP get请求
     *
     * @param url     请求的URL地址
     * @param json    请求的JSON对象
     * @param charset 编码
     * @param sslpath 请求证书地址
     * @param sslpass 证书密码
     * @return 请求相应的字符串
     */
    public static String doPostSSL(String url, Object json, String charset, String sslpath, String sslpass) throws Exception {
        return doPostSSL(url, json, charset, null, sslpath, sslpass);
    }

    /**
     * 执行一个HTTP POST请求
     *
     * @param url     请求的URL地址
     * @param json    请求的JSON参数
     * @param charset 编码
     * @param headers 要传递的cookie
     * @return 请求相应的字符串
     */
    public static String doPost(String url, Object json, String charset, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        } else {
            httpPost.reset();
        }
        StringEntity stringEntity = new StringEntity(json.toString(), charset);
        stringEntity.setContentEncoding(charset);
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == SUCCESS) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, charset);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 执行一个HTTP POST请求
     *
     * @param url     请求的URL地址
     * @param json    请求的JSON参数
     * @param charset 编码
     * @param headers 要传递的cookie
     * @return 请求相应的字符串
     */
    public static String doPostSSL(String url, Object json, String charset, Map<String, String> headers, String sslpath, String sslpass) throws Exception {
        if (S.isEmpty(charset)) {
            charset = DEFAULT_CHART_SET;
        }

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(sslpath));
        try {
            keyStore.load(instream, sslpass.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStore, sslpass.toCharArray())
            .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            new String[]{"TLSv1"},
            null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            //.setConnectionManager(connMgr)
            .build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        } else {
            httpPost.reset();
        }
        StringEntity stringEntity = new StringEntity(json.toString(), charset);
        stringEntity.setContentEncoding(charset);
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == SUCCESS) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, charset);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
